package com.example.chat.receptionist.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.chat.common.constant.DigitConstant;
import com.example.chat.common.utils.ConvertUtils;
import com.example.chat.receptionist.dao.ReceptionistDAO;
import com.example.chat.receptionist.pojo.dto.ReceptionistDTO;
import com.example.chat.receptionist.pojo.entity.ReceptionistEntity;
import com.example.chat.receptionist.service.ReceptionistService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ReceptionistServiceImpl implements ReceptionistService {
    @Resource
    ReceptionistDAO receptionistDAO;

    @Override
    public void save(ReceptionistDTO receptionistDTO) {
        receptionistDAO.insert(ConvertUtils.of(receptionistDTO, ReceptionistEntity.class));
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        ReceptionistEntity receptionistEntity = new ReceptionistEntity();
        receptionistEntity.setStatus(status);
        receptionistEntity.setId(id);
        receptionistDAO.updateById(receptionistEntity);
    }

    @Override
    public ReceptionistDTO assign() {
        QueryWrapper<ReceptionistEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(ReceptionistEntity.STATUS, DigitConstant.ONE);
        wrapper.last("ORDER BY RAND() LIMIT 1");
        List<ReceptionistEntity> receptionistEntities = receptionistDAO.selectList(wrapper);

        ReceptionistEntity receptionistEntity;
        if (CollectionUtils.isEmpty(receptionistEntities)) {
            // 随便分配一个离线客服
            QueryWrapper<ReceptionistEntity> wrapper2 = new QueryWrapper<>();
            wrapper2.eq(ReceptionistEntity.STATUS, DigitConstant.ZERO);
            receptionistEntity = receptionistDAO.selectOne(wrapper2);
        } else {
            receptionistEntity = receptionistEntities.get(0);
        }

        return ConvertUtils.of(receptionistEntity, ReceptionistDTO.class);
    }

}
